<template>
  <!--入库-->
  <div class="pur">
    <!--仓库标签页-->
    <el-row>
      <el-tabs v-model="warehouseValue" @tab-click="changeWar(warehouseValue)">
        <el-tab-pane label="全部仓库" name="0"></el-tab-pane>
        <el-tab-pane
          :key="index"
          v-for="(item, index) in warehouseList"
          :label="item.warehouseName"
          :name="item.warehouseId+''">
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <!--入库查找-->
    <el-row>
      <span style="padding: 0 10px"><i class="font-14 el-icon-s-open"></i></span>
      <el-select v-model="filterValue" value-key="value" @change="initData(currPage,pageSize,filterValue,warId,content)" placeholder="全部数据" style="width: 120px">
        <el-option v-for="group in filterOptions" :key="group.value"
                   :label="group.label" :value="group.value">
        </el-option>
      </el-select>
      <span style="padding: 0 10px 0 30px"><i class="fn el-icon-message-solid"></i></span>
      <el-input v-model="content" clearable placeholder="请输入内容" style="width: 150px"></el-input>
      <el-select v-model="vagueValue" placeholder="主题" style="width: 120px">
        <el-option v-for="group in vagueOptions" :key="group.value"
                   :label="group.label" :value="group.value">
        </el-option>
      </el-select>
      <el-button @click="initData(currPage,pageSize,filterValue,warId,content)" icon="el-icon-search" size="small" circle></el-button>
    </el-row>
    <!--入库单-->
    <div style="margin-top: 15px;overflow: hidden;">
      <el-col :span="12" class="m-b-10">
        <span>入库单</span>
        <small class="text-muted font-13">共{{totalSize}}条</small>
      </el-col>
      <!--入库单dialog-->
      <el-dialog title="入库单" :visible.sync="dialogFormVisible" @close="closeDialog" width="60%" style="color: #333333"  >
        <el-form :model="storage" label-width="100px">
          <el-divider><span class="font-14-bold"></span></el-divider>
          <el-row>
            <el-col>
              <el-form-item label="主题:">
                <el-input v-model="storage.storageTheme" style="width: 91%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仓库:">
                <el-select v-model="storage.warehouseByWarehouseId" value-key="warehouseId" placeholder="未选" style="width: 79%">
                  <el-option :disabled="true" v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填单时间:">
                <el-input :disabled="true" v-model="storage.storageDate" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态:">
                <el-select v-model="storage.storageStatus" placeholder="未选" style="width: 79%">
                  <el-option :disabled="true" v-for="item in ztsOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填单人:">
                <el-input :disabled="true" v-model="storage.employeeByStoEmployeeId.empName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="库管确认:">
                <el-input v-if="this.storage.employeeByAffEmployeeId !== null" :disabled="true" v-model="storage.employeeByAffEmployeeId.empName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行时间:">
                <el-input :disabled="true" v-model="storage.storageExecutorDate" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对应采购单:">
                <el-input :disabled="true" v-model="storage.purchaseByPurchaseId.purchaseTheme" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对应退货单:">
                <el-input v-if="this.storage.returnByReturnId !== null" :disabled="true" v-model="storage.returnByReturnId.returnTheme" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对应供应商:">
                <el-input :disabled="true" v-model="storage.customerByCustomerId.customerName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="备注:">
                <el-input v-model="storage.storageNote" style="width: 91%" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="入库明细:" style="width: 92%">
                <el-row>
                  <div class="detail">
                    <el-table :data="detailList" style="width: 100%" border show-summary>
                      <el-table-column type="index" label="序号" width="50">
                      </el-table-column>
                      <el-table-column prop="productByProductId.productName" label="产品名" >
                      </el-table-column>
                      <el-table-column prop="productByProductId.productModel" label="型号" >
                      </el-table-column>
                      <el-table-column prop="storageDetailNum" label="入库量" >
                      </el-table-column>
                      <el-table-column prop="storageDetailNote" label="备注" >
                      </el-table-column>
                    </el-table>
                  </div>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="8">
              <el-form-item>
                <span v-if="this.storage.storageStatus === 1">
                  <el-button @click="addStorage" type="primary">保存</el-button>
                  <el-button @click="dialogFormVisible = false">取消</el-button>
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <!--方案表格-->
    <el-table ref="multipleTable" :data="storageList" tooltip-effect="dark" id="outTable"
              style="width: 100%" border :header-cell-style="rowClass">
      <el-table-column prop="storageId" label="ID" sortable width="80"></el-table-column>
      <el-table-column label="主题" width="130">
        <template slot-scope="scope">
          <div @click="handleEdit(scope.row)" style="color: #333333" class="cursor">
            <i class="el-icon-caret-right"></i>
            <span>{{scope.row.storageTheme}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseByWarehouseId.warehouseName" label="仓库" width="105"></el-table-column>
      <el-table-column prop="storageDate" label="填单时间" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.storageDate | formatDateJudge}}</span>
        </template>
      </el-table-column>
      <el-table-column label="对应采购单">
        <template slot-scope="scope">
          <span>{{scope.row.purchaseByPurchaseId.purchaseTheme}}</span>
          <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
            <router-link :to="{path:'/purchaseview',query: {purId: scope.row.purchaseByPurchaseId.purchaseId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
            </router-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="对应供应商">
        <template slot-scope="scope">
          <span>{{scope.row.customerByCustomerId.customerName}}</span>
          <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
            <router-link :to="{path:'/customerview',query: {customerId: scope.row.customerByCustomerId.customerId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
            </router-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" >
        <template slot-scope="scope">
          <span v-if="scope.row.storageStatus === 1">{{ztsOptions[0].label}}</span>
          <span v-if="scope.row.storageStatus === 2">{{ztsOptions[1].label}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="employeeByAffEmployeeId.empName" label="填单人"></el-table-column>
      <el-table-column prop="storageExecutorDate" label="执行日期" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.storageExecutorDate | formatDateJudge}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130">
        <template slot-scope="scope">
          <div>
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
              <el-button size="mini" @click="handleEdit(scope.row) "
                         icon="el-icon-s-ticket" type="primary" circle style="margin-left: 10px"></el-button>
            </el-tooltip>
            <span v-if="scope.row.storageStatus === 1">
              <el-tooltip  class="item" effect="dark" content="编辑明细确认入库" placement="bottom">
              <el-button  size="mini" @click="openSto(scope.row.storageId)"
                        icon="el-icon-edit-outline" type="primary" circle plain></el-button>
              </el-tooltip>
            </span>
            <span v-if="scope.row.storageStatus === 1">
             <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <el-button size="mini" @click="handleDelete(scope.row)"
                         icon="el-icon-delete" type="danger" circle></el-button>
              </el-tooltip>
            </span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="margin-top:10px">
      <el-col :offset="8" :span="14">
        <el-pagination layout="sizes,prev,pager, next, jumper" :total="totalSize" @current-change="changePage"
                       :current-page.sync="currPage" :page-size="pageSize" :page-sizes="pageSizes" @size-change="changeSize"></el-pagination>
      </el-col>
      <el-col :span="2">
        <el-tooltip class="item" effect="dark" content="打印列表" placement="bottom">
          <el-button @click="handleWindowPrint('#outTable', '列表打印')" style="padding: 12px 12px" type="info" plain  icon="el-icon-printer"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="导出Excel格式数据" placement="bottom">
          <el-button @click="exportExcel" style="padding: 12px 12px" type="info" plain  icon="el-icon-document-remove"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
  </div>

</template>

<script>
  import {formatTimeToStr} from "../assets/format";
  import XLSX from "xlsx";
  import FileSaver from "file-saver";
  export default {
    data () {
      return {
        emp:{},
        dialogFormVisible: false,
        storageList: [], // 入库集合分页
        detailList: [], // 明细集合
        warehouseList: [],// 仓库集合
        warehouseValue: '0',
        warId:0,// 默认仓库值
        pageSize: 10, // 分页页大小
        pageSizes:[10,20,30],//页大小数组
        currPage: 1, // 当前页码，默认为1
        totalSize: 0, // 总记录数
        storage: {
          storageId: 0,
          storageTheme: '',
          storageDate: '',
          storageStatus: '',
          storageNote: '',
          storageExecutorDate: '',
          customerByCustomerId: '',
          employeeByStoEmployeeId: '',
          employeeByAffEmployeeId: '',
          purchaseByPurchaseId: '',
          returnByReturnId: '',
          warehouseByWarehouseId: ''
        },
        content: '',// input内容
        filterOptions: [{
          value: 0,
          label: '全部数据',
        },{
          value: 1,
          label: '未入库',
        }, {
          value: 2,
          label: '已入库',
        }],
        filterValue: 0,
        vagueOptions: [{
          value: 1,
          label: '主题'
        }],
        vagueValue: 1,
        ztsOptions: [{
          value: 1,
          label: '未入库'
        },{
          value: 2,
          label: '已入库'
        }],
      }
    },
    methods: {
      // 查询当前员工
      loginEmp() {
        this.$axios.get('http://localhost:8088/emp')
          .then(v => {
            this.emp = v.data
          })
          .catch(function (v) {
          })
      },
      // 分页查询所有
      initData(currPage, pageSize,status,warId,content) {
        this.$axios.get('http://localhost:8088/sto-list', {
          params: {
            page: currPage,
            size: pageSize,
            status:status,
            warId:warId,
            stoTheme:content
          }
        })
          .then(v => {
            this.storageList = v.data.rows
            this.totalSize = v.data.total
          })
          .catch(function (v) {
          })
      },
      // 入库表格分页
      changePage(val) {
        this.initData(val, this.pageSize,this.filterValue,this.warId,this.content)
      },
      //改变页大小
      changeSize(val){
        this.pageSize = val
        this.currPage = 1
        this.initData(this.currPage,this.pageSize,this.filterValue,this.warId,this.content)
      },
      // 查询所有详单
      findDetail(stoId) {
        this.$axios.get('http://localhost:8088/sto-detail-list', {
          params: {
            stoId: stoId
          }
        })
          .then(v => {
            this.detailList = v.data
          })
          .catch(function (v) {
          })
      },
      // 查询所有仓库
      findWarehouse() {
        this.$axios.get('http://localhost:8088/war-list')
          .then(v => {
            this.warehouseList = v.data
          })
          .catch(function (v) {
          })
      },
      // 修改数据回显
      handleEdit(val) {
        this.dialogFormVisible = true
        this.storage.storageId = val.storageId
        this.storage.storageTheme = val.storageTheme
        this.storage.storageDate = val.storageDate
        this.storage.storageStatus = val.storageStatus
        this.storage.storageNote = val.storageNote
        this.storage.storageExecutorDate = val.storageExecutorDate
        this.storage.customerByCustomerId = val.customerByCustomerId
        this.storage.employeeByStoEmployeeId = val.employeeByStoEmployeeId
        if(val.employeeByAffEmployeeId === null){
          this.storage.employeeByAffEmployeeId = ''
        }else {
          this.storage.employeeByAffEmployeeId = val.employeeByAffEmployeeId
        }
        if(val.returnByReturnId === null){
          this.storage.returnByReturnId = ''
        }else {
          this.storage.returnByReturnId = val.returnByReturnId
        }
        this.storage.purchaseByPurchaseId = val.purchaseByPurchaseId
        this.storage.warehouseByWarehouseId = val.warehouseByWarehouseId
        this.findDetail(val.storageId)
      },
      // 新增、修改
      addStorage() {
        if(this.storage.employeeByAffEmployeeId == ''){
          this.storage.employeeByAffEmployeeId = null
        }
        if(this.storage.returnByReturnId == ''){
          this.storage.returnByReturnId = null
        }
        this.$axios.post('http://localhost:8088/save-storage',
          {
            storageId: this.storage.storageId,
            storageTheme: this.storage.storageTheme,
            storageDate: this.storage.storageDate,
            storageStatus: this.storage.storageStatus,
            storageNote: this.storage.storageNote,
            storageExecutorDate: this.storage.storageExecutorDate,
            warehouseByWarehouseId: this.storage.warehouseByWarehouseId,
            employeeByStoEmployeeId: this.storage.employeeByStoEmployeeId,
            employeeByAffEmployeeId: this. storage.employeeByAffEmployeeId,
            purchaseByPurchaseId: this.storage.purchaseByPurchaseId,
            returnByReturnId: this.storage.returnByReturnId,
            customerByCustomerId: this.storage.customerByCustomerId,
            storageDetailsByStorageId: this.detailList
          })
          .then(v => {
            // 1、刷新数据
            this.initData(this.currPage,this.pageSize,this.filterValue,this.warId,this.content)
            // 2、关闭弹框
            this.dialogFormVisible = false
            this.$message({
              message: '已保存',
              type: 'success'
            });
          })
          .catch(function (v) {
          })
      },
      // 关闭dialog事件
      closeDialog() {
        this.storage = {
          storageId: 0,
          storageTheme: '',
          storageDate: '',
          storageStatus: '',
          storageNote: '',
          storageExecutorDate: '',
          customerByCustomerId: '',
          employeeByStoEmployeeId: '',
          employeeByAffEmployeeId: '',
          purchaseByPurchaseId: '',
          returnByReturnId: '',
          warehouseByWarehouseId: ''
        }
        this.detailList = []
      },
      // 点击编辑详单跳转到报价视图
      openSto(stoId) {
        if (this.storage.storageStatus === 2){
          this.$message({
            message: '该入库单已入库，不可编辑明细',
            type: 'warning'
          });
        }else {
          this.$router.push({path: '/storageview', query: {stoId: stoId}});
        }
      },
      // 删除提示
      handleDelete(val) {
        this.$confirm('此操作将永久删除该入库单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteSto(val.storageId)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 删除axios
      deleteSto(stoId) {
        this.$axios.post('http://localhost:8088/delete-storage',
          this.qs.stringify({stoId: stoId}))
          .then(v => {
            // 1、刷新数据
            this.initData(this.currPage,this.pageSize,this.filterValue,this.warId,this.content)
          })
          .catch(function (v) {
          })
      },
      // 选择仓库
      changeWar(val){
        this.warId = Number(val)
        this.initData(this.currPage,this.pageSize,this.filterValue,this.warId,this.content)
      },
      // pdf打印
      handleWindowPrint (ele, fileName) {
        document.body.innerHTML = document.querySelector(ele).outerHTML
        // 转异步 等待dom元素渲染（样式）完毕在打印
        setTimeout(() => {
          // 打印
          window.print()
          // 刷新页面
          window.location.reload()
        }, 20)
      },
      //导出excel
      exportExcel () {
        var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
        var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
            "库存流水导出.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },
      // 表头靠左样式
      rowClass(){
        return "text-align:left"
      }
    },
    created() {
      this.loginEmp()
      this.initData(this.currPage,this.pageSize,this.filterValue,this.warId,this.content)
      this.findWarehouse()
    },
    filters: {
      formatDate: function(time) {
        if(time!=null&&time!="")
        {
          var date = new Date(time);
          return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
        }else{
          return "";
        }
      },
      formatDateJudge: function(time) {
        if(time != null && time != "")
        {
          let date = new Date(time);
          let currentDate = new Date()
          let seperator1 = "-";
          let month = currentDate.getMonth() + 1<10? "0"+(currentDate.getMonth() + 1):currentDate.getMonth() + 1;
          let strDate = currentDate.getDate()<10? "0" + currentDate.getDate():currentDate.getDate();
          let today = currentDate.getFullYear() + seperator1  + month  + seperator1  + strDate
          let todayTime = new Date(today)
          let yesterday = todayTime.setDate(todayTime.getDate() - 1)
          let beforeYesterday = todayTime.setDate(todayTime.getDate() - 1)
          let tomorrow = todayTime.setDate(todayTime.getDate() + 3)
          let afterTomorrow = todayTime.setDate(todayTime.getDate() + 1)
          todayTime.setDate(todayTime.getDate() - 2)
          if (date.getTime() === todayTime.getTime()){
            return '今天'
          }else if (date.getTime() ===  yesterday){
            return '昨天'
          }else if (date.getTime() ===  beforeYesterday){
            return '前天'
          }else if (date.getTime() ===  tomorrow){
            return '明天'
          }else if (date.getTime() ===  afterTomorrow){
            return '后天'
          }else {
            return time
          }
        }else{
          return "";
        }
      }
    }
  }
</script>

<style>
</style>

